import {
  getCabinetQualityByPage,
  addCabinetQuality,
  updateCabinetQuality,
  delCabinetQuality,
  getWorkOrderInforAndproductName,
  getWos,
  exportCabinetQuality,
  getBatchPlanByPage,
  getCabinetErrorByPage,
  getProcessNamesByWo,
  delCabinetError,
  getErroType,
  getCabinetError,
  getCabinetQualityInformationByWo,
  getProductManufactExecInfosByWoId,
  addCabinetQualityAndCabinetError,
  editCabinetQualityAndCabinetError,
  getWorkOrderInforByWo,
  getBatchPlanCode,
} from '@/services/quality/cabinetQuality';
import { PlusOutlined } from '@ant-design/icons';
import moment from 'moment';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Button,
  Form,
  Input,
  message,
  Modal,
  DatePicker,
  InputNumber,
  Select,
  AutoComplete,
} from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import dayjs from 'dayjs';
import React, { useRef, useState } from 'react';
import { EditableProTable } from '@ant-design/pro-table';

import weekday from 'dayjs/plugin/weekday';
import localeData from 'dayjs/plugin/localeData';
import { tableSearchPublicConfig } from '@/utils/filterUtils';
import { getProjectNameAndCodeSimp } from '@/services/quality/customComplaint';
import { Ellipsis } from '@/components/Ellipsis';

dayjs.extend(weekday);
dayjs.extend(localeData);

const CabinetQuality: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const editorFormRef = useRef<any>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [projectInfos, setProjectInfos] = useState(); //所有项目名称和编号
  const [projectOptions, setProjectOptions] = useState<any[]>(); //项目编号options
  const [editWorkOrder, setEditWorkOrder] = useState(true); //工序框的可编辑
  const [workInfo, setWorkInfo] = useState();
  const [editFlag, setEditFlag] = useState(false);
  const [workCodeOptions, setWorkCodeOptions] = useState();
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  const [batchOptions, setBatchOptions] = useState(); //批次信息
  const [errorOptions, setErrorOptions] = useState(); //错误类型
  const [orderOptions, setOrderOptions] = useState(); //工序
  const [errorAll, setErrorAll] = useState(0); //
  const [form] = Form.useForm();
  const dateFormat = 'YYYY-MM-DD HH:mm';
  const now = new Date();
  const year = now.getFullYear(); // 获取年份，如 2023
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 获取月份，需要加1，如 05
  const day = String(now.getDate()).padStart(2, '0'); // 获取日期，如 23
  const hours = String(now.getHours()).padStart(2, '0'); //获取小时
  const minutes = String(now.getMinutes()).padStart(2, '0'); //获取分钟
  const currentTime = `${year}-${month}-${day} ${hours}:${minutes}`; //格式化当前时间
  const ref = useRef(null);
  let submit_1 = {
    cabinetErrorDtos: {
      cabinetQualityId: '',
      errorLineCount: 0,
      errorType: '',
      id: '',
      processName: '',
    },
    cabinetQualityDto: {
      batchCount: 0,
      batchPlanCode: '',
      batchPlanId: '',
      currentBatch: 0,
      errorLineCount: 0,
      id: '',
      inspectTime: '',
      inspector: '',
      lineCount: 0,
      memo: '',
      productCode: '',
      productName: '',
      wo: '',
    },
  };
  let submit_error = {
    cabinetQualityId: '',
    id: '',
  };

  //获取下拉框的数据
  const getSelectInfo = async () => {
    //工单
    console.log('youshadongxi ', form.getFieldsValue());
    const temp: any[] = [];
    const info = form.getFieldsValue().wo;
    console.log('info', info);
    const result = await getWos(info);
    console.log('获取的wo', result);
    if (result != null) {
      result.data.map((item: any) => {
        temp.push({ label: item, value: item });
      });
    }
    setWorkCodeOptions(temp);
  };

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      sorter: true,
      width: 80,
    },
    {
      title: '项目编号',
      dataIndex: 'projectCode',
      align: 'center',
      sorter: true,
      width: 145,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      align: 'center',
      sorter: true,

      width: 200,
    },
    {
      title: '当前批次',
      dataIndex: 'currentBatch',
      align: 'center',
      sorter: true,
      width: 100,
      search: false,
      // render: (text) => <>{Ellipsis(text)}</>,
      render: (text, record) => (
        <div>
          {text}/{record.batchCount}
        </div>
      ),
    },
    /*     {
      title: '批次编号',
      align: 'center',
      sorter: true,
      dataIndex: 'batchPlanCode',

      width: 180,
    }, */
    {
      title: '工单编号',
      dataIndex: 'wo',
      align: 'center',
      sorter: true,
      width: 200,
    },
    {
      title: '柜体编号',
      dataIndex: 'productCode',
      key: 'productCode',
      align: 'center',
      sorter: true,
      width: 200,
    },
    {
      title: '柜体描述',
      dataIndex: 'productDesc',
      align: 'center',
      sorter: true,
      width: 160,
      render: (text) => <>{Ellipsis(text)}</>,
    },

    /* {
      title: '批次总数',
      dataIndex: 'batchCount',
     align: 'center',sorter: true, 
      search: false,
    }, */
    {
      title: '接线错误总数',
      align: 'center',
      sorter: true,
      dataIndex: 'errorLineCount',
      width: 100,
      search: false,
      /* render: (text, record, _, action) => <span>{errorAll}</span>, */
    },
    /*  {
      title: '接线错误数量',
      dataIndex: 'errorLineCount',
      search: false,
     align: 'center',sorter: true, 
    }, */
    {
      title: '接线总数量',
      dataIndex: 'lineCount',
      search: false,
      align: 'center',
      sorter: true,
      width: 100,
    },
    {
      title: '填报时间',
      search: false,

      dataIndex: 'inspectTime',
      width: 150,
      align: 'center',
      sorter: true,
      render: (text, record) => <a>{moment(record.inspectTime).format('YYYY-MM-DD HH:mm')}</a>,
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,
      dataIndex: 'createName',
      width: 60,
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,

      width: 100,
      render: (text, record) => <div>{moment(text).format('YYYY-MM-DD')}</div>,
      dataIndex: 'createTime',
    },
    /* {
      title: '备注',
     align: 'center',sorter: true, 
      search: false,
      dataIndex: 'memo',
    }, */
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={async (value) => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            //setEditWorkOrder(false);
            getSelectInfo();
            setEditFlag(true);
            setFormTitle('编辑');

            /* const result = await getProjectNameAndCodeSimp();
            setProjectInfos(result.data);
            const temp: any[] = [];
            result.data.map((item: any) => {
              temp.push({ label: item.projectName, value: item.projectName });
            });
            setProjectOptions(temp);
            console.log('获得的项目名称数据', result, projectOptions); */
            form.setFieldsValue({
              projectName: record.projectName,
              batchCount: record.batchCount,
              projectCode: record.projectCode,
              batchPlanCode: record.batchPlanCode,
              currentBatch: record.currentBatch,
              errorLineCount: record.errorLineCount,
              inspectTime: dayjs(record.inspectTime),
              lineCount: record.lineCount,
              productCode: record.productCode,
              memo: record.memo,
              productName: record.productName,
              wo: record.wo,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delCabinetQuality({ id: record.id });
                actionRef.current!.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const errorColumns: ProColumns[] = [
    {
      title: '错误类型',
      dataIndex: 'errorType',
      renderFormItem: () => <Select placeholder="请选择错误类型" options={errorOptions} />,
    },
    {
      title: '工序',
      dataIndex: 'processName',
      renderFormItem: () => (
        <Select
          placeholder="请选择工序"
          options={orderOptions}
          //disabled={editWorkOrder}
          onClick={async (value: any) => {
            const wo_id = form.getFieldsValue();
            console.log('这是在干什么', wo_id);
            /* const work1 = await getWorkOrderInforByWo(wo_id.wo);
            const workId = work1.data.id;
            console.log('工单id', workId); */
            const temp: any[] = [];
            const resultOrder = await getProcessNamesByWo(wo_id.wo);
            console.log('收到的工序11', resultOrder);
            if (resultOrder.data != null) {
              resultOrder.data.map((item: any) => {
                temp.push({ label: item, value: item }); //label和value应该都是字符串
              });
            }
            setOrderOptions(temp);
          }}
        />
      ),
    },
    {
      title: '接线错误数量 ',
      dataIndex: 'errorLineCount',
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
            form.setFieldsValue({
              errorType: record.errorType,
              errorLineCount: record.errorLineCount,
              processName: record.processName,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            action?.startEditable?.(record.id);
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                const res = form.getFieldsValue();
                console.log('现在的数据', res);
                submit_error.id = record.id;
                submit_error.cabinetQualityId = res.id;
                console.log('我现在要提交这些删除', submit_error);
                await delCabinetError(submit_error);
                actionRef?.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  //大表单提交
  const handleSubmit = async (values, data) => {
    /* saveSubmitError(data); */
    setConfirmLoading(true);
    if (formTitle == '新建') {
      form
        .validateFields()
        .then(async () => {
          const res = form.getFieldsValue();
          console.log(res, '原本的submit1');
          submit_1.cabinetErrorDtos = res.cabinetErrorDtos;
          //console.log(submit_1, '修改的submit1');
          delete res.cabinetErrorDtos;
          submit_1.cabinetQualityDto = res;
          const woInfo = await getCabinetQualityInformationByWo(res.wo);
          submit_1.cabinetQualityDto.productCode = woInfo.data.productCode;
          submit_1.cabinetQualityDto.batchPlanCode = woInfo.data.batchPlanCode;
          res.inspectTime = dayjs(res.inspectTime).format(dateFormat);
          console.log(submit_1, '提交的submit1', submit_1.cabinetQualityDto.productCode);
          const result = await addCabinetQualityAndCabinetError(submit_1);
          console.log('新建', result);
          if (result != null) {
            message.success('添加成功');
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current!.reload();
        })
        .catch((err) => {
          setConfirmLoading(false);
        });
    } else {
      form
        .validateFields()
        .then(async () => {
          /* const res = { ...form.getFieldsValue() };
          res.inspectTime = dayjs(res.handleTime).format(dateFormat);
          const result = await editCabinetQualityAndCabinetError(res);
          console.log('编辑', res);
          if (result != null) {
            message.success('更新成功');
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current!.reload(); */
          const res = form.getFieldsValue();
          console.log(res, '原本的submit1');
          submit_1.cabinetErrorDtos = res.cabinetErrorDtos;
          //console.log(submit_1, '修改的submit1');
          delete res.cabinetErrorDtos;
          submit_1.cabinetQualityDto = res;
          //console.log(submit_1, '提交的submit1');
          res.inspectTime = dayjs(res.inspectTime).format(dateFormat);
          const result = await editCabinetQualityAndCabinetError(submit_1);
          console.log('编辑', result);
          if (result != null) {
            message.success('编辑成功');
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current!.reload();
        })
        .catch((err) => {
          setConfirmLoading(false);
        });
    }
  };

  const workCodeChange = async (e) => {
    const result = workInfo!.find((item: any) => {
      return item.workOrderCode === e;
    }).productName;
    form.setFieldsValue({
      productName: result,
    });
  };

  //获取工序类型
  const handleChange = async (value: any) => {
    console.log(`selected ${value}`);
    /* const work1 = await getWorkOrderInforByWo(value);
    const workId = work1.data.id;
    console.log('工单id', workId); */
    const temp: any[] = [];
    const resultOrder = await getProcessNamesByWo(value);
    console.log('收到的工序', resultOrder);
    if (resultOrder.data != null) {
      resultOrder.data.map((item: any) => {
        temp.push({ label: item, value: item }); //label和value应该都是字符串
      });
    }
    setOrderOptions(temp);
    //setEditWorkOrder(false);
  };
  //每条error的保存
  const saveSubmitError = async (data) => {
    console.log('data', data);
    form.validateFields().then(async () => {
      const res = form.getFieldsValue();
      console.log(submit_1, '原本的submit1');
      submit_1.cabinetErrorDtos = data;
      setErrorAll(Number(errorAll) + Number(data.errorLineCount));
      delete res.cabinetErrorDtos;
      submit_1.cabinetQualityDto = res;
      console.log(submit_1, '提交的submit1');
      const result = await addCabinetQualityAndCabinetError(submit_1);
      console.log('我说真的result', result);
      if (result != null) {
        message.success('修改成功');
        /*  setConfirmLoading(false);
        setModalVisit(false); */
        actionRef.current!.reload();
      }
    });
    /* .catch(() => {
        setConfirmLoading(false);
      }); */
  };

  const handleSearch = (search) => {
    const filteredOptions = workCodeOptions.filter((option) =>
      option.label.toLowerCase().includes(search.toLowerCase()),
    );
    setWorkCodeOptions(filteredOptions);
  };

  //下拉框搜索匹配
  const filterOption = (input: string, option: { label: string; value: string }) =>
    (option?.label ?? '').toLowerCase().includes(input.toLowerCase());

  //切换项目名称时，修改项目编号
  const changeProjectCode = async (e: string) => {
    const projectCode = projectInfos!.find((item: any) => {
      return item.projectName === e;
    }).projectCode;
    form.setFieldsValue({
      projectCode: projectCode,
    });
    console.log('youshadongxi ', form.getFieldsValue());
    const temp: any[] = [];
    const info = form.getFieldsValue().projectCode;
    console.log('info', info);
    try {
      const result = await getWos(info);
      console.log('获取的wo', result);
      if (result != null) {
        result.data.map((item: any) => {
          temp.push({ label: item, value: item });
        });
      }
      setWorkCodeOptions(temp);
    } catch (error) {
      // 处理错误
    }
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="接线质量填报查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={{
          ...tableSearchPublicConfig,
        }}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={async () => {
              const result = await getWorkOrderInforAndproductName();
              setWorkInfo(result.data);
              const temp: any[] = [];
              result.data.map((item: any) => {
                temp.push({ label: item.workOrderCode, value: item.workOrderCode });
              });
              setWorkCodeOptions(temp);
              getSelectInfo();
              setEditFlag(false);
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
              console.log(dayjs(currentTime));
              form.setFieldsValue({
                inspectTime: dayjs(currentTime),
              });
            }}
            type="primary"
          >
            新建
          </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              const filters = filterTran(ref.current!.getFieldsValue());
              exportCabinetQuality({
                current: 1,
                pageSize: 5000,
                filters: filters,
              }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `CabinetQuality.xls`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }}
            type="primary"
          >
            导出
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const sorters = sortTran(sort);
          const filters = filterTran(params);
          const result = await getCabinetQualityByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          console.log('大页面', result);
          // 获取批次信息resultBatch
          const tempBatch: any[] = [];
          const resultBatch = await getBatchPlanCode({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          resultBatch.data.map((item: any) => {
            tempBatch.push({ label: item, value: item });
          });
          setBatchOptions(tempBatch);
          const result11 = await getProjectNameAndCodeSimp();
          setProjectInfos(result11.data);
          const temp11: any[] = [];
          result11.data.map((item: any) => {
            temp11.push({ label: item.projectName, value: item.projectName });
          });
          setProjectOptions(temp11);
          // console.log('获得的项目名称数据', result11, projectOptions, '项目信息', projectInfos);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 1200, y: 350 }}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        open={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => {
          setModalVisit(false);
        }}
        width={850}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '130px' }}
          labelAlign="right"
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item name="id" label="id" hidden={true}></Form.Item>
          <Form.Item
            name="projectName"
            label="项目名称"
            rules={[{ required: true, message: '请选择项目!' }]}
          >
            <Select
              showSearch
              filterOption={filterOption}
              placeholder="请选择项目名称"
              options={projectOptions}
              disabled={editFlag}
              onChange={async (e) => {
                changeProjectCode(e);
              }}
            />
          </Form.Item>
          <Form.Item
            name="projectCode"
            label="项目编号"
            rules={[{ required: true, message: '请输入项目编号!' }]}
          >
            <Input disabled />
          </Form.Item>
          {/* <Form.Item
            name="batchPlanCode"
            label="批次编号"
            rules={[{ required: true, message: '请输入批次编号 !' }]}
          >
            <Select placeholder="请选择批次编号" options={batchOptions} />
          </Form.Item> */}
          <Form.Item
            name="wo"
            label="工单编号"
            rules={[{ required: true, message: '请输入工单编号!' }]}
          >
            <AutoComplete
              options={workCodeOptions}
              onSearch={handleSearch}
              onChange={getSelectInfo}
              disabled={editFlag}
              status="warning"
              style={{ width: 670 }}
            />

            {/*  <Select
              placeholder="请选择工单编号"
              options={workCodeOptions}
              onChange={handleChange}
              disabled={createOrUpdate}
            /> */}
          </Form.Item>
          <Form.Item
            /* initialValue="1" */
            name="lineCount"
            label="接线总数量"
            rules={[{ required: true, message: '请输入接线总数量!' }]}
          >
            <InputNumber style={{ width: 670 }} min={1} onChange={() => {}} />
          </Form.Item>
          <Form.Item
            name="inspectTime"
            label="填报时间"
            rules={[{ required: true, message: '请输入填报日期!' }]}
          >
            <DatePicker
              showTime={{ format: 'HH:mm' }}
              format="YYYY-MM-DD HH:mm"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item name="errorLineCount" label="接线错误总数" tooltip="自动累加">
            <InputNumber disabled style={{ width: 670 }}></InputNumber>
            {/* <InputNumber disabled style={{ width: 670 }}></InputNumber> */}
          </Form.Item>
          <Form.Item name="cabinetErrorDtos">
            <EditableProTable
              /* editable={{
                onSave: saveSubmitError,
              }} */
              value={dataSource}
              actionRef={actionRef}
              recordCreatorProps={{
                record: () => {
                  return {
                    id: `0${Date.now()}`,
                  };
                },
              }}
              request={async (params = {}, sort, filter) => {
                const temp: any[] = [];
                const sorters = sortTran(sort);
                const filters = filterTran(params);
                const result = await getErroType(null);
                result.data.map((item: any) => {
                  temp.push({ label: item, value: item });
                });
                setErrorOptions(temp); //接线错误的选项
                /* const result_1 = await getCabinetErrorByPage({
                  ...params,
                  sorters: sorters,
                  filters: filters,
                });
                console.log('小表', result_1); */
                const res = form.getFieldsValue();
                if (res.id == null) {
                  res.id = 0;
                }
                const result_1 = await getCabinetError(res.id);
                console.log('小表', result_1);
                return {
                  data: result_1.data,
                  total: result_1.data.totalElements,
                  success: result_1.success,
                };
              }}
              onChange={setDataSource}
              columns={errorColumns}
              rowKey="id"
            />
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default CabinetQuality;
